//
//  KKStatusPictureView.swift
//  SinaWeiBo
//
//  Created by King.Kong. on 16/5/27.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit
//图片之间的间距
private let pictureMargin: CGFloat = 3
//最大宽度
private let maxWidth = ScreenWidth - 2 * StatusCellMargin
//单张图片的宽度
private let itemWidth = (maxWidth - 2 * pictureMargin) / 3

private let pictureCellId = "pictureCellId"

class KKStatusPictureView: UICollectionView {
    
    //数据源
    var pictures: [KKPicture]? {
        didSet {
            
            testLabel.text = "\(pictures?.count ?? 0)"
            //print(pictures?.count)
            //根据图片的数量 更新 大小的 约束
            let pSize = calculatePictureViewSize()
            self.snp_updateConstraints { (make) in
                make.size.equalTo(pSize)
            }
            
            
            // TODO:一定要记住 数据一旦发生了额变化 就应该刷新列表
            reloadData()
        }
    }
    
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        //设置间距
        layout.minimumLineSpacing = pictureMargin
        layout.minimumInteritemSpacing = pictureMargin
        super.init(frame: frame, collectionViewLayout: layout)
        //设置数据源代理
        self.dataSource = self
        // 设置代理
        self.delegate = self
        backgroundColor = UIColor.whiteColor()
        
        //设置不能响应点击状态栏快速回到的 手势
        scrollsToTop = false
        
        //注册
        registerClass(KKStatusPictureCell.self, forCellWithReuseIdentifier: pictureCellId)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(testLabel)
        //设置约束
        testLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self.snp_center)
        }
    }
    
    private lazy var testLabel: UILabel = UILabel(title: "",textColor: UIColor.redColor(), font: 30)
    
    //需要根据配图视图的显示的数据的 '数量' 来确定配图视图的大小
    /*
     1. 单张图片按照图片的原比例来显示
     2. 四张图片按照 2 * 2 对称显示
     3. 其他的多张图片 n * 3 形式来显示
     */
    
    func calculatePictureViewSize() -> CGSize {
        let imageCount = pictures?.count ?? 0
        //0张图
        if imageCount == 0 {
            return CGSizeZero
        }
        
        //获取collectioView的布局对象
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //1张图片
        if imageCount == 1 {
            //图片原比例
            //TODO: 后面完善
            let imageSize = CGSizeMake(100, 150)
            //还需要设置itemSize 和 图片一样大
            layout.itemSize = imageSize
            return imageSize
        }
        
        //设置其他多张图片的itemSize
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //四张图片
        if imageCount == 4 {
            // 2 * 2
            let w = itemWidth * 2 + pictureMargin
            return CGSizeMake(w, w)
        }
        
        //程序走到这里 就是其他的多张图片
        //1. 根据图片张数 计算 行数
        /*
         1,2,3   1
         4,5,6   2
         7,8,9   3
         */
        let row = CGFloat((imageCount - 1) / 3) + 1
        let maxHeight = row * itemWidth + (row - 1) * pictureMargin
        return CGSizeMake(maxWidth, maxHeight)
    }
}

//MARK: DataSource
extension KKStatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellId, forIndexPath: indexPath) as! KKStatusPictureCell
        cell.backgroundColor = randomColor()
        //给cell的模型赋值
        cell.picture = pictures![indexPath.item]
        return cell
    }
    //实现代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = pictures?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        
        }

}

extension KKStatusPictureView: SDPhotoBrowserDelegate {
    //返回原来现实的小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        //获取点击的cell
        //返回cell的iconView的image
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indexPath) as! KKStatusPictureCell
        return cell.imageView.image
    }
    
    //返回的高清图片的url地址
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        //获取缩略图的地址
        let urlString = pictures![index].thumbnail_pic
        //修改地址中的 thumbnail 为 bimiddle 或者 large
        let middleurlString = urlString?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        let url = NSURL(string: middleurlString!)
        return url
    }
}


class KKStatusPictureCell: UICollectionViewCell {
    //给cell 设置模型
    var picture: KKPicture? {
        didSet {
            let url = NSURL(string: picture?.thumbnail_pic ?? "")
            
            imageView.sd_setImageWithURL(url)
        }
    }
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        
        contentView.addSubview(imageView)
        //设置约束
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    //懒加载控件
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        //手写代码需要自动设置裁剪 xib/sb会自动设置裁剪
        iv.clipsToBounds = true
        return iv
    }()
}


